package com.thinkgem.jeesite.common.persistence;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author:Kongxiangsheng
 * @DesCription:
 * @Date:Created in 16:13 2018/8/7
 * @Modified By:
 */
public class BasePage<T> extends com.baomidou.mybatisplus.extension.plugins.pagination.Page {
    /**
     * 首页索引
     */
    private int first;
    /**
     * 尾页索引
     */
    private int last;
    /**
     * 上一页索引
     */
    private int prev;
    /**
     * 下一页索引
     */
    private int next;
    /**
     * 是否是第一页
     */
    private boolean firstPage;

    /**
     * 是否是最后一页
     */
    private boolean lastPage;

    /**
     * 显示页面长度
     */
    private int length = 8;

    /**
     * 前后显示页面长度
     */
    private int slider = 1;

    /**
     * 标准查询有效， 实例： updatedate desc, name asc
     */
    private String orderBy = "";

    /**
     * 设置点击页码调用的js函数名称，默认为page，在一页有多个分页对象时使用。
     */
    private String funcName = "page";

    /**
     * 函数的附加参数，第三个参数值。
     */
    private String funcParam = "";

    /**
     * 设置提示消息，显示在“共n条”之后
     */
    private String message = "";

    public BasePage() {
    }

    /**
     * 构造方法
     *
     * @param request  传递 repage 参数，来记住页码
     * @param response 用于设置 Cookie，记住页码
     */
    public BasePage(HttpServletRequest request, HttpServletResponse response) {
        this(request, response, -2);
    }

    /**
     * 构造方法
     *
     * @param request         传递 repage 参数，来记住页码
     * @param response        用于设置 Cookie，记住页码
     * @param defaultPageSize 默认分页大小，如果传递 -1 则为不分页，返回所有数据
     */
    public BasePage(HttpServletRequest request, HttpServletResponse response, int defaultPageSize) {
        // 设置页码参数（传递repage参数，来记住页码）
        String no = request.getParameter("pageCurrent");
        if (StringUtils.isNumeric(no)) {
            CookieUtils.setCookie(response, "pageCurrent", no);
            this.setCurrent(Integer.parseInt(no));
        } else if (request.getParameter("repage") != null) {
            no = CookieUtils.getCookie(request, "pageCurrent");
            if (StringUtils.isNumeric(no)) {
                this.setCurrent(Integer.parseInt(no));
            }
        }
        // 设置页面大小参数（传递repage参数，来记住页码大小）
        String size = request.getParameter("pageSize");
        if (StringUtils.isNumeric(size)) {
            CookieUtils.setCookie(response, "pageSize", size);
            this.setSize(Integer.parseInt(size));
        } else if (request.getParameter("repage") != null) {
            size = CookieUtils.getCookie(request, "pageSize");
            if (StringUtils.isNumeric(size)) {
                this.setSize(Integer.parseInt(size));
            }
        } else if (defaultPageSize != -2) {
            this.setSize(defaultPageSize);
        }
        // 设置页面分页函数
        String funcName = request.getParameter("funcName");
        if (StringUtils.isNotBlank(funcName)) {
            CookieUtils.setCookie(response, "funcName", funcName);
            this.setFuncName(funcName);
        } else if (request.getParameter("repage") != null) {
            funcName = CookieUtils.getCookie(request, "funcName");
            if (StringUtils.isNotBlank(funcName)) {
                this.setFuncName(funcName);
            }
        }
        // 设置排序参数
        String orderBy = request.getParameter("orderBy");
        if (StringUtils.isNotBlank(orderBy)) {
            this.setOrderBy(orderBy);
        }
    }

    /**
     * 构造方法
     *
     * @param pageNo   当前页码
     * @param pageSize 分页大小
     */
    public BasePage(int pageNo, int pageSize) {
        this(pageNo, pageSize, 0);
    }

    /**
     * 构造方法
     *
     * @param pageNo   当前页码
     * @param pageSize 分页大小
     * @param count    数据条数
     */
    public BasePage(int pageNo, int pageSize, long count) {
        this(pageNo, pageSize, count, new ArrayList<T>());
    }

    /**
     * 构造方法
     *
     * @param pageNo   当前页码
     * @param pageSize 分页大小
     * @param count    数据条数
     * @param list     本页数据对象列表
     */
    public BasePage(int pageNo, int pageSize, long count, List<T> list) {
        this.setTotal(count);
        this.setCurrent(pageNo);
        this.setSize(pageSize);
        this.setRecords(list);
    }

    /**
     * 初始化参数
     */
    private void initialize() {
        this.first = 1;

        this.last = (int) (this.getTotal() / (this.getSize() < 1 ? 20 : this.getSize()) + first - 1);

        if (this.getTotal() % this.getSize() != 0 || this.last == 0) {
            this.last++;
        }

        if (this.last < this.first) {
            this.last = this.first;
        }

        if (this.getCurrent() <= 1) {
            this.setCurrent(this.first);
            this.firstPage = true;
        }

        if (this.getCurrent() >= this.last) {
            this.setCurrent(this.last);
            this.lastPage = true;
        }

        if (this.getCurrent() < this.last - 1) {
            this.next = (int)(this.getCurrent() + 1);
        } else {
            this.next = this.last;
        }

        if (this.getCurrent() > 1) {
            this.prev = (int)(this.getCurrent() - 1);
        } else {
            this.prev = this.first;
        }

        //2
        // 如果当前页小于首页
        if (this.getCurrent() < this.first) {
            this.setCurrent(this.first);
        }
        // 如果当前页大于尾页
        if (this.getCurrent() > this.last) {
            this.setCurrent(this.last);
        }

    }

    /**
     * 默认输出当前分页标签
     * <div class="page">${page}</div>
     */
    @Override
    public String toString() {
        initialize();

        StringBuilder sb = new StringBuilder();

        // 首页特殊处理
        if (this.getCurrent() == first) {
            sb.append("<li class=\"disabled\"><a href=\"javascript:\">&#171; 上一页</a></li>\n");
        } else {
            sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + prev + "," + this.getSize() + ",'" + funcParam + "');\">&#171; 上一页</a></li>\n");
        }

        int begin = (int)(this.getCurrent() - (length / 2));

        if (begin < first) {
            begin = first;
        }

        int end = begin + length - 1;

        if (end >= last) {
            end = last;
            begin = end - length + 1;
            if (begin < first) {
                begin = first;
            }
        }

        if (begin > first) {
            int i = 0;
            for (i = first; i < first + slider && i < begin; i++) {
                sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + i + "," + this.getSize() + ",'" + funcParam + "');\">"
                        + (i + 1 - first) + "</a></li>\n");
            }
            if (i < begin) {
                sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n");
            }
        }

        for (int i = begin; i <= end; i++) {
            if (i == this.getCurrent()) {
                sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first)
                        + "</a></li>\n");
            } else {
                sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + i + "," + this.getSize() + ",'" + funcParam + "');\">"
                        + (i + 1 - first) + "</a></li>\n");
            }
        }

        if (last - end > slider) {
            sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n");
            end = last - slider;
        }

        for (int i = end + 1; i <= last; i++) {
            sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + i + "," + this.getSize() + ",'" + funcParam + "');\">"
                    + (i + 1 - first) + "</a></li>\n");
        }

        if (this.getCurrent() == last) {
            sb.append("<li class=\"disabled\"><a href=\"javascript:\">下一页 &#187;</a></li>\n");
        } else {
            sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + next + "," + this.getSize() + ",'" + funcParam + "');\">"
                    + "下一页 &#187;</a></li>\n");
        }

        sb.append("<li class=\"disabled controls\"><a href=\"javascript:\">当前 ");
        sb.append("<input type=\"text\" value=\"" + this.getCurrent() + "\" onkeypress=\"var e=window.event||event;var c=e.keyCode||e.which;if(c==13)");
        sb.append(funcName + "(this.value," + this.getSize() + ",'" + funcParam + "');\" onclick=\"this.select();\"/> / ");
        sb.append("<input type=\"text\" value=\"" + this.getSize() + "\" onkeypress=\"var e=window.event||event;var c=e.keyCode||e.which;if(c==13)");
        sb.append(funcName + "(" + this.getCurrent() + ",this.value,'" + funcParam + "');\" onclick=\"this.select();\"/> 条，");
        sb.append("共 " + this.getTotal() + " 条" + (message != null ? message : "") + "</a></li>\n");

        sb.insert(0, "<ul>\n").append("</ul>\n");

        sb.append("<div style=\"clear:both;\"></div>");

//		sb.insert(0,"<div class=\"page\">\n").append("</div>\n");

        return sb.toString();
    }

    /**
     * 获取分页HTML代码
     *
     * @return
     */
    public String getHtml() {
        return toString();
    }

    /**
     * 首页索引
     *
     * @return
     */
    @JsonIgnore
    public int getFirst() {
        return first;
    }

    /**
     * 尾页索引
     *
     * @return
     */
    @JsonIgnore
    public int getLast() {
        return last;
    }

    /**
     * 获取页面总数
     *
     * @return getLast();
     */
    @JsonIgnore
    public int getTotalPage() {
        return getLast();
    }

    /**
     * 是否为第一页
     *
     * @return
     */
    @JsonIgnore
    public boolean isFirstPage() {
        return firstPage;
    }

    /**
     * 是否为最后一页
     *
     * @return
     */
    @JsonIgnore
    public boolean isLastPage() {
        return lastPage;
    }

    /**
     * 上一页索引值
     *
     * @return
     */
    @JsonIgnore
    public int getPrev() {
        long prev = 0;
        if (isFirstPage()) {
            prev = this.getCurrent();
        } else {
            prev = this.getCurrent() - 1;
        }
        return (int)prev;
    }

    /**
     * 下一页索引值
     *
     * @return
     */
    @JsonIgnore
    public int getNext() {
        long next = 0;
        if (isLastPage()) {
            next = this.getCurrent();
        } else {
            next = this.getCurrent() + 1;
        }
        return (int)next;
    }

    /**
     * 获取查询排序字符串
     *
     * @return
     */
    @JsonIgnore
    public String getOrderBy() {
        // SQL过滤，防止注入
        String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
                + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
        Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
        if (sqlPattern.matcher(orderBy).find()) {
            return "";
        }
        return orderBy;
    }

    /**
     * 设置查询排序，标准查询有效， 实例： updatedate desc, name asc
     */
    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    /**
     * 获取点击页码调用的js函数名称
     * function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;}
     *
     * @return
     */
    @JsonIgnore
    public String getFuncName() {
        return funcName;
    }

    /**
     * 设置点击页码调用的js函数名称，默认为page，在一页有多个分页对象时使用。
     *
     * @param funcName 默认为page
     */
    public void setFuncName(String funcName) {
        this.funcName = funcName;
    }

    /**
     * 获取分页函数的附加参数
     *
     * @return
     */
    @JsonIgnore
    public String getFuncParam() {
        return funcParam;
    }

    /**
     * 设置分页函数的附加参数
     *
     * @return
     */
    public void setFuncParam(String funcParam) {
        this.funcParam = funcParam;
    }

    /**
     * 设置提示消息，显示在“共n条”之后
     *
     * @param message
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * 分页是否有效
     *
     * @return this.pageSize==-1
     */
    @JsonIgnore
    public boolean isDisabled() {
        return this.getSize() == -1;
    }

    /**
     * 是否进行总数统计
     *
     * @return this.count==-1
     */
    @JsonIgnore
    public boolean isNotCount() {
        return this.getTotal() == -1;
    }

    /**
     * 获取 Hibernate FirstResult
     */
    public int getFirstResult() {
        long firstResult = (this.getCurrent() - 1) * this.getSize();
        if (firstResult >= this.getTotal()) {
            firstResult = 0;
        }
        return (int)firstResult;
    }

    /**
     * 获取 Hibernate MaxResults
     */
    public int getMaxResults() {
        return (int)this.getSize();
    }
}
